/**
 * Created by quxiangqian on 2018/7/7.
 */

export class CheckBox extends React.Component {
    state={
        item:false,
        error:false,
        message:"",
    }
    onChange=(e,item)=>{
        //item.value=e.target.value;
        if(!e.target.checked){
            console.log("数据源：",this.state.item.value.split(",").filter((it)=>it!==e.target.value));
            this.state.item.value=this.convasString(this.state.item.value.split(",").filter((it)=>it!==e.target.value));

        }else{
            let arr= [];
           if(this.state.item.value!==""){
                arr= this.state.item.value.split(",");
           }
           arr.push(e.target.value);
           this.state.item.value=this.convasString(arr);
            //this.state.item.value.push(e.target.value);
            //a=this.state.item.value;
        }
        this.setState({item:this.state.item});
    }

    showError=(message)=>{
        this.state.error=false;
        this.setState({error:false,message:message});
    }

    default=()=>{
        this.setState({error:false});
    }


    convasString=(arr)=>{
      let str="";
      for(let i=0;i<arr.length;i++){
        if(i>0){
          str+=","
        }
        str+=arr[i];
      }
      return str;
    }
    include=(values,val)=>{
       return values.split(",").filter(it=>it===val).length>0;
    }

    render(){
        if(!this.state.item){
            this.state.item= this.props.bind[this.props.name];
          //  console.log(this.state.item.value);
        }

        if(!this.state.item.showError){
            this.state.item.showError=this.showError;
        }
        if(!this.state.item.default){
            this.state.item.default=this.default;
        }

        let tem=(<label style={{marginRight:'1rem'}}>
            <input style={{marginRight:'0.5rem'}}
                   onClick={(e)=>{this.onChange(e,this.state.item)}}
                   type="checkbox"
                   ref={(da)=>{
                        if(da){
                            if(this.include(this.state.item.value,this.props.value)){
                                da.checked=true;
                            }else{
                                da.checked=false;
                            }
                        }
        }}  name={this.props.name}  value={this.props.value} ></input>{this.props.text}</label>)

        return tem;
    }
}
